//
//  GameManagedObject.m
//  prototype
//
//  Created by OS X on 11-12-18.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "GameManagedObject.h"
#import "PlayerManagedObject.h"


@implementation GameManagedObject

+ (GameManagedObject *)gameWithResult:(NSDictionary *)result inManagedContext:(NSManagedObjectContext *)context
{
    GameManagedObject *game = [NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:context];    
    game.date = [result objectForKey:@"date"];
    
    NSNumberFormatter *n = [[NSNumberFormatter alloc] init];
    
    game.draw = [n numberFromString:[result objectForKey:@"draw"]];
    game.player1 = [result objectForKey:@"player1"]; // Winner is expected to arrive at the player1 key
    game.player2 = [result objectForKey:@"player2"];
    game.pvp = [n numberFromString:[result objectForKey:@"pvp"]];

    // Construct dictionary for player
    NSDictionary *player1 = [NSDictionary dictionaryWithObjectsAndKeys:
                            game.player1, @"name",
                            [n numberFromString:[result objectForKey:@"ai_1"]], @"ai", //untested
                             (game.draw.intValue==1)? @"1":@"0", @"draw",
                             @"1", @"winner", nil];
    
    NSDictionary *player2 = [NSDictionary dictionaryWithObjectsAndKeys:
                             game.player2, @"name",
                             [n numberFromString:[result objectForKey:@"ai_2"]], @"ai", //untested
                             (game.draw.intValue==1)? @"1":@"0", @"draw",
                             @"0", @"winner", nil];

    // Create the players for this game
    game.players = [NSOrderedSet orderedSetWithObjects:
                    [PlayerManagedObject playerWithResult:player1 inManagedContext:context],
                    [PlayerManagedObject playerWithResult:player2 inManagedContext:context], nil];
    return game;
}

@dynamic date;
@dynamic replay;
@dynamic draw;
@dynamic player1;
@dynamic player2;
@dynamic pvp;
@dynamic moves;
@dynamic players;

@end
